package com.ccc3gc.util;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
    private static DataSource ds = null;

    static {
        Properties properties = new Properties();
        try (
                //InputStream fis = new FileInputStream("src/JdbcUtils.properties")
                InputStream fis = JdbcUtils.class.getResourceAsStream("/JdbcUtils.properties")
        ) {
            properties.load(fis);
        } catch (Exception e) {
            throw new RuntimeException();
        }
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        ds = new DriverManagerDataSource(url, user, password);
    }

    public static JdbcTemplate getJdbcTemplate() {
        return new JdbcTemplate(ds);
    }

    public static Connection startTransaction() {
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.initSynchronization();
        }
        Connection connection = DataSourceUtils.getConnection(ds);
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    public static void commit(Connection connection) {
        try {
            connection.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            clear(connection);
        }
    }

    public static void rollback(Connection connection) {
        try {
            connection.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            clear(connection);
        }
    }

    private static void clear(Connection connection) {
        TransactionSynchronizationManager.clear();
        TransactionSynchronizationManager.unbindResourceIfPossible(ds);
        DataSourceUtils.releaseConnection(connection, ds);
    }
}
